<template>
  <!--- 上报隐患 -->
  <view>
    <view class="container">
      <uni-forms ref="form" :modelValue="formData" labelWidth="120px" labelPosition="top">
        <view class="hidden-title">信息填写</view>
        <cu-cell-group>
          <uni-forms-item name="managerType">
            <cu-cell
              title="隐患类型"
              required
              link
              placeholder="请选择隐患类型"
              :description="managerTypeLabel"
              @click="managerTypeClick()"
            ></cu-cell>
          </uni-forms-item>
          <uni-forms-item name="managerLevel">
            <cu-cell
              title="隐患级别"
              required
              link
              placeholder="请选择隐患级别"
              :description="managerLevelLabel"
              @click="managerLevelClick()"
            ></cu-cell>
          </uni-forms-item>
          <uni-forms-item name="majorHiddenDangerType" v-if="importantDangerValue == formData.managerLevel">
            <cu-cell
              title="重大隐患判定依据"
              required
              link
              placeholder="请选择重大隐患判定依据"
              :description="majorHiddenDangerName"
              @click="dangerSourceClick()"
            ></cu-cell>
          </uni-forms-item>
          <uni-forms-item name="deptId" v-if="!deviceID">
            <cu-cell title="所属部门" link placeholder="请选择" :description="deptLabel" @click="deptClick()"></cu-cell>
          </uni-forms-item>
          <uni-forms-item name="userId" v-if="!deviceID">
            <cu-cell title="负责人" link placeholder="请选择" :description="authLabel" @click="userClick()"></cu-cell>
          </uni-forms-item>
        </cu-cell-group>
        <view class="background-white bor-top" v-if="!deviceID">
          <uni-forms-item name="location" label="隐患位置">
            <textarea
              v-model="formData.location"
              class="text-area"
              placeholder="请输入隐患位置信息(限50字)"
              placeholder-class="form-placeholder__style"
              maxlength="50"
            />
          </uni-forms-item>
        </view>
        <view class="background-white bor-top">
          <uni-forms-item name="managerDesc" label="隐患描述">
            <textarea
              v-model="formData.managerDesc"
              class="text-area"
              placeholder="对发生的隐患进行简要描述,方便治理人员快速判断需要做的准备(限100字)"
              maxlength="100"
            />
          </uni-forms-item>
        </view>
        <view class="background-white bor-top">
          <uni-forms-item label="隐患分析">
            <textarea
              v-model="formData.managerAnalysis"
              class="text-area"
              placeholder="对隐患产生 的原因做简要的分析"
              maxlength="100"
            />
          </uni-forms-item>
        </view>

        <view class="background-white bor-top">
          <uni-forms-item label="上传照片（最多3张）" labelWidth="150">
            <image-upload state="edit" :imageUrl="formData.reportPhotoUrl" @change="imageOnChange"> </image-upload>
          </uni-forms-item>
        </view>
      </uni-forms>

      <dict-picker ref="managerTypeDict" title="隐患类型" dictType="dbd_manager_type" @confirm="manageTypeOnConfirm">
      </dict-picker>
      <dict-picker ref="managerLevelDict" title="隐患级别" dictType="dbd_manager_level" @confirm="manageLevelOnConfirm">
      </dict-picker>
      <manager-level-picker
        ref="managerLevelPicker"
        title="重大隐患判定依据"
        :data="managerLevelList"
        @confirm="managerLevelConfirm"
      ></manager-level-picker>

      <dept-selector ref="deptDict" title="检修部门" @change="deptConfirm"> </dept-selector>
      <user-selector ref="userDict" title="负责人" @change="userConfirm"> </user-selector>
    </view>
    <view class="container">
      <view class="hidden-title">隐患信息</view>
      <view class="background-white" style="margin-bottom: 200rpx">
        <view class="flex text bor-btm"
          >所属重大危险源：
          <text>{{
            detail.dangerSourceFlag === 'N' || !detail.dangerSourceFlag ? '无' : detail.dangerSourceLabel
          }}</text>
        </view>
        <view class="flex text bor-btm"
          >所属风险区域：
          <text>--</text>
        </view>
        <view class="flex text bor-btm"
          >隐患项：
          <text>{{ formData.mangerName }}</text>
        </view>
        <view class="flex text bor-btm" v-if="deviceID"
          >所属部门：
          <text>{{ detail.deptName }}</text>
        </view>
        <view class="flex text bor-btm" v-if="deviceID"
          >隐患位置：
          <text>{{ detail.installationLocation }}</text>
        </view>
        <view class="flex text bor-btm"
          >隐患来源：
          <text>智能巡检</text>
        </view>
        <view class="flex text" v-if="deviceID"
          >负责人：
          <text>{{ detail.dutyUserName }}</text>
        </view>
      </view>
    </view>

    <view class="submit-group">
      <button class="u-button" type="primary" :ripple="true" @click="submit">上报</button>
    </view>
  </view>
</template>

<script>
import { report, getMajorHiddenDangerType } from '@/api/dbd/hiddenDangerReport.js'
import { getDicts } from '@/api/system/dict.js'
import { getDeviceStandingBookById, deviceHiddenDangerManage } from '@/api/equipment/standingBook.js'

import CuCellGroup from '@/components/cu-cell/cu-cell-group.vue'
import CuCell from '@/components/cu-cell/cu-cell.vue'
import DictPicker from '@/components/dict-picker/index.vue'
import DataPicker from '@/components/data-picker/index.vue'
import ImageUpload from '@/components/image-upload/index.vue'
import DeptSelector from '@/components/dept-selector/index.vue'
import UserSelector from '@/components/user-selector/index.vue'

import ManagerLevelPicker from '../../components/ManagerLevelPicker.vue'
export default {
  components: {
    CuCellGroup,
    CuCell,
    DictPicker,
    DataPicker,
    ImageUpload,
    ManagerLevelPicker,
    DeptSelector,
    UserSelector
  },
  props: {},
  data() {
    return {
      deptLabel: '',
      authLabel: '',
      formData: {
        //隐患项
        mangerName: '',
        //隐患类型
        managerType: '',
        //隐患级别
        managerLevel: '',
        //所属风险区域
        areaId: null,
        //所属重大危险源
        dangerSourceId: null,
        // 隐患位置
        location: '',
        //隐患描述
        managerDesc: '',
        // 隐患分析
        managerAnalysis: '',
        // 默认隐患来源智能巡检
        managerSource: '18',
        // 现场照片
        reportPhotoUrl: '',
        // 隐患排查子任务id
        dangerPlanSubTaskId: null,
        deptId: '', //所属部门
        userId: '', //责任人
        // 重大隐患判定依据id
        majorHiddenDangerType: '',
        managerSourceId: ''
      },
      deviceID: '',
      spareParts: '',
      detail: {
        deptName: '',
        dutyUserName: '',
        installationLocation: '',
        dangerSourceFlag: '',
        dangerSourceLabel: ''
      },
      rules: {
        managerType: {
          rules: [
            {
              required: true,
              errorMessage: '隐患类型不能为空'
            }
          ]
        },
        location: {
          rules: [
            {
              required: true,
              errorMessage: '隐患位置不能为空'
            }
          ]
        },
        managerLevel: {
          rules: [
            {
              required: true,
              errorMessage: '隐患级别不能为空'
            }
          ]
        },
        managerDesc: {
          rules: [
            {
              required: true,
              errorMessage: '隐患描述不能为空'
            }
          ]
        },
        majorHiddenDangerType: {
          rules: [
            {
              required: true,
              errorMessage: '重大隐患判定依据不能为空'
            }
          ]
        },
        reportPhotoUrl: {
          rules: [
            {
              required: true,
              errorMessage: '照片不能为空'
            }
          ]
        }
      },
      managerTypeLabel: '',
      managerLevelLabel: '',
      managerLevelList: [],
      importantDangerValue: '',
      // 重大安全隐患名
      majorHiddenDangerName: ''
    }
  },
  onLoad({ deviceId, spareParts, inspectionContent }) {
    this.deviceID = deviceId && deviceId !== 'null' ? deviceId : ''
    this.spareParts = spareParts
    if (this.deviceID) {
      getDeviceStandingBookById(this.deviceID).then(({ data }) => {
        Object.keys(this.detail).forEach((item) => {
          this.detail[item] = data[item] ?? this.detail[item]
        })
        this.formData.dangerSourceId = data.dangerSourceId
        this.formData.deptId = data.deptId
        this.formData.location = data.installationLocation
        this.formData.userId = data.dutyUserId
        if (this.spareParts) {
          this.formData.mangerName = data.deviceName + '[' + this.spareParts + ']'
        } else {
          this.formData.mangerName = data.deviceName
        }

        this.formData.areaId = data.areaId
      })
    } else {
      this.formData.mangerName = inspectionContent + '异常'
    }
    this.getDBDManagerLevelList()
    this.getManagerLevelList()
  },
  onReady() {
    this.$refs.form.setRules(this.rules)
  },
  beforeDestroy() {},
  methods: {
    userClick() {
      this.$refs.userDict.open()
    },
    userConfirm(obj) {
      this.authLabel = obj.name
      this.formData.userId = obj.value
    },
    deptClick() {
      this.$refs.deptDict.open()
    },
    deptConfirm(obj) {
      this.deptLabel = obj.name
      this.formData.deptId = obj.value
    },
    managerLevelConfirm(obj) {
      this.formData.majorHiddenDangerType = obj.value
      this.formData.managerDesc = obj.name
      this.majorHiddenDangerName = obj.name
    },
    getManagerLevelList() {
      getMajorHiddenDangerType().then((res) => {
        this.managerLevelList = res.data
      })
    },
    navigateBack() {
      uni.navigateBack()
    },
    // 获取隐患级别
    getDBDManagerLevelList() {
      getDicts('dbd_manager_level').then((res) => {
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].dictLabel == '一般隐患') {
            this.managerLevelLabel = res.data[i].dictLabel
            this.formData.managerLevel = res.data[i].dictValue
          }
          if (res.data[i].dictLabel == '重大隐患') {
            this.importantDangerValue = res.data[i].dictValue
          }
        }
      })
    },
    managerTypeClick() {
      this.$refs.managerTypeDict.open()
    },
    manageTypeOnConfirm(obj) {
      this.managerTypeLabel = obj.name
      this.formData.managerType = obj.value
    },
    managerLevelClick() {
      this.$refs.managerLevelDict.open()
    },
    manageLevelOnConfirm(obj) {
      this.managerLevelLabel = obj.name
      this.formData.managerLevel = obj.value
      // this.rules.dangerSource.rules[0].required = obj.name === '重大隐患'
      // this.$nextTick(() => {
      // 	this.$refs.form.setRules(this.rules)
      // })
    },

    dangerSourceClick() {
      this.$refs.managerLevelPicker.open()
    },
    imageOnChange(urlList) {
      this.formData.reportPhotoUrl = urlList.join(',')
    },
    submit() {
      this.$refs.form.validate().then((res) => {
        this.$modal.confirm('确定上报隐患？').then(() => {
          report(this.formData).then(({ data }) => {
            this.$modal.showToast('上报成功')
            //设备关联隐患
            if (this.deviceID) {
              deviceHiddenDangerManage({
                hiddenDangerMangerId: data,
                deviceId: this.deviceID
              })
            }
            // 调用正常接口
            this.checkNormal()
          })
        })
      })
    },
    checkNormal() {
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.emit('callback:success')
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss">
.container {
  .background-white {
    background-color: #fff;
    padding: 20rpx 30rpx;
    box-sizing: border-box;

    .uni-forms-item__label {
      color: #333;
      font-size: 30rpx;
    }

    .bor-btm {
      display: flex;
      border-bottom: 1px solid #d5d7e3;
    }

    .photo {
      display: flex;
      justify-content: space-between;

      image {
        width: 214rpx;
        height: 214rpx;
      }
    }

    .text {
      padding-bottom: 20rpx;
      padding-top: 4rpx;
      color: #333;

      text {
        color: #666;
      }
    }
  }
}

.hidden-title {
  background: #f5f5f5;
  padding: 20rpx;
  color: #999;
}

.bor-top {
  border-top: 20rpx solid #f5f5f5;
}

.submit-group {
  background: #fff;
  z-index: 9;
  padding: 30px;
}
.u-button {
  width: 600rpx;
}
</style>
